import json
import os

from django.shortcuts import render
from django.http import HttpResponse, HttpResponseRedirect
from MyApp.models import *
from django.contrib import auth
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
import random
from django.contrib.auth.hashers import make_password
from django.core.mail import send_mail
from django.conf import settings
import shutil
import subprocess
import re


@login_required(login_url='/login/')
def project_list(request):  # 项目列表
    project_list = DB_project.objects.all()
    button = [{'path': 'javascript: project_data()', 'icon': 'list', 'name': '项目数据'},
              {'path': '/add_project/', 'icon': 'folder', 'name': '新增项目'}]
    project_name = '项目列表页'
    return render(request, 'project_list.html',
                  {'projects': project_list, 'buttons': button, 'project_name': project_name})


# 新增项目
def add_project(request):
    project = DB_project.objects.create(name='xxxxxxx', creater='admin')
    shutil.copy('MyApp/mitm_edits/mitm_edit.py', 'MyApp/mitm_edits/%s_mitm_edit.py' % project.id)
    return HttpResponseRedirect('/project_list/')


# 删除项目
def del_project(request, pid):
    DB_project.objects.filter(id=pid).delete()
    DB_Mock.objects.filter(project_id=pid).delete()
    try:
        os.remove('MyApp/mitm_edits/%s_mitm_edit.py' % pid)
    except:
        ...
    return HttpResponseRedirect('/project_list')


# 项目设置
def project_set(request):
    project_new_name = request.GET.get('project_new_name')
    project_id = request.GET.get('project_id')
    DB_project.objects.filter(id=project_id).update(name=project_new_name)
    return HttpResponse('')


# 项目数据
def project_data(request):
    res = ''
    projects = DB_project.objects.all()
    for project in projects:
        res += '[' + str(project.id) + ']' + '\n'
        res += '[' + project.name + ']' + '\n'
        res += '[' + project.creater + ']' + '\n'
        res += '[' + str(project.run_counts) + ']' + '\n'
        res += '[' + str(project.mock_counts) + ']' + '\n'

        res += str(len(DB_Mock.objects.filter(project_id=project.id)))
        res += '<br>'
    return HttpResponse(res)


# 登陆页面
def login(request):
    return render(request, 'login.html')


# 登出
def logout(request):
    auth.logout(request)  # 为什么呢？
    return HttpResponseRedirect('/login')


# 登陆
def sign_in(request):
    # 获取用户的用户名，密码
    username = request.POST.get('in_username')
    password = request.POST.get('in_password')
    # 到数据库查看是否有这个人
    user = auth.authenticate(username=username, password=password)
    # 有则登陆成功
    if user is not None:
        # 下面两句没懂
        auth.login(request, user)
        request.session['user'] = username
        return HttpResponse('001')
    # 没有则给提示，还在这个界面
    else:
        return HttpResponse('000')


# 注册
def sign_up(request):
    # 拿到用户名，密码，邮箱
    up_username = request.GET.get('up_username')
    up_password = request.GET.get('up_password')
    up_email = request.GET.get('up_email')
    # 注册成功
    try:
        user = User.objects.create_user(username=up_username, password=up_password, email=up_email)
        user.save()
        auth.login(request, user)
        request.session['user'] = up_username
        return HttpResponseRedirect('/project_list/')
    # 有就返回错误提示
    except:
        return HttpResponse('用户已存在，请重新注册')


# 忘记密码
def forget_pwd(request):
    # 拿到用户名，验证码，邮箱
    username = request.GET.get('fg_username')
    password = request.GET.get('fg_password')
    code = request.GET.get('fg_code')

    # # 只判断验证码
    # if code == User.objects.filter(username=username)[0].last_name:
    #     User.objects.filter(username=username).update(password=make_password(password))
    # return HttpResponseRedirect('/login/')
    # else:
    #     return HttpResponse('请重新输入')

    # 直接判断用户存不存在
    user = User.objects.filter(username=username, password=password, last_name=code)
    if user is not None:
        User.objects.filter(username=username).update(password=make_password(password))
        return HttpResponseRedirect('/login/')
    else:
        return HttpResponse('请重新输入')


# 发送邮件-验证码
def send_email_code(request):
    # 拿到用户名
    username = request.GET.get('fg_username')
    # 根据用户名拿到邮箱
    email = User.objects.filter(username=username)[0].email
    # 生成随机验证码
    code = str(random.randint(1000, 9999))
    # 保存到数据库某个字段（临时）
    User.objects.filter(username=username).update(last_name=code)
    # 发送到邮箱
    message = '验证码:' + code
    send_mail('Mock平台找回密码', message, settings.EMAIL_FROM, [email])
    return HttpResponse('yes')


# 项目详情页
def mock_list(request, pid):
    mock_list = DB_Mock.objects.filter(project_id=pid)
    project = DB_project.objects.filter(id=pid)[0]
    button = [{'path': '/add_mock/%s/' % project.id, 'icon': 'folder-open', 'name': '新增单元'},
              {'path': '/server_enable/%s' % project.id, 'icon': 'folder-open', 'name': '启动服务'},
              {'path': '/server_disable/%s' % project.id, 'icon': 'folder-open', 'name': '关闭服务'},
              {'path': '//', 'icon': 'folder-open', 'name': '抓包导入'},
              {'path': 'javascript: project_set()', 'icon': 'hand-pointer-o', 'name': '项目设置'},
              ]
    project_name = '项目详情页(%s) ' % project.name + '  port:' + str(9000 + project.id)
    project_id = project.id
    project_state = '服务状态：%s' % project.state
    return render(request, 'mock.html',
                  {'mocks': mock_list, 'buttons': button, 'project_name': project_name, 'project_id': project_id,
                   'project_state': project_state})


# 新增mock单元
def add_mock(request, pid):
    DB_Mock.objects.create(name='xxxx', project_id=pid)
    return HttpResponseRedirect('/mock_list/%s/' % pid)


# 删除mock单元
def del_mock(request, mid):
    mock = DB_Mock.objects.filter(id=mid)
    project_id = mock[0].project_id
    mock.delete()
    return HttpResponseRedirect('/mock_list/%s/' % project_id)


# 拿到mock数据
def get_mock(request):
    mock_id = request.GET.get('mock_id')
    mock = DB_Mock.objects.filter(id=mock_id).values()[0]
    res = {'mock': mock}
    return HttpResponse(json.dumps(res), content_type='application/json')


# mock 设置
def mock_set(request):
    mock_id = request.GET['mock_id']
    mock_name = request.GET.get('mock_name')
    mock_catch_url = request.GET.get('mock_catch_url')
    mock_response_body = request.GET.get('mock_response_body')
    DB_Mock.objects.filter(id=mock_id).update(name=mock_name,
                                              catch_url=mock_catch_url,
                                              response_body=mock_response_body)
    return HttpResponse('')


# 启用单元
def mock_enable(request, mid):
    mock = DB_Mock.objects.filter(id=mid)
    mock.update(status=True)
    project_id = mock[0].project_id
    return HttpResponseRedirect('/mock_list/%s/' % project_id)


# 弃用单元
def mock_disable(request, mid):
    mock = DB_Mock.objects.filter(id=mid)
    mock.update(status=False)
    project_id = mock[0].project_id
    return HttpResponseRedirect('/mock_list/%s/' % project_id)


# 启用服务
def server_enable(request, pid):
    port = str(9000 + int(pid))
    script = 'MyApp/mitm_edits/%s_mitm_edit.py' % pid
    cmd = 'mitmdump -p %s -s %s' % (port, script)
    subprocess.call(cmd, shell=True)
    DB_project.objects.filter(id=pid).update(state=True)
    return HttpResponseRedirect('/mock_list/%s' % pid)


# 关闭服务
def server_disable(request, pid):
    port = str(9000 + int(pid))
    cmd = 'ps -ef |grep mitm |grep %s' % port
    res = subprocess.check_output(cmd, shell=True)
    for i in str(res).split('\\n'):
        if pid + '_mitm_edit.py' in i:
            max_id = max([int(i) for i in re.findall(r'\d+', i.split('/')[0])])
            cmd2 = 'kill -9 %s' % str(max_id)
            subprocess.check_output(cmd2, shell=True)
            print('进程已杀死')
            break
    else:
        print('进程未找到')
    DB_project.objects.filter(id=pid).update(state=False)
    return HttpResponseRedirect('/mock_list/%s' % pid)


########测试模块
def demo_span(request):
    # print('收到')
    return HttpResponse('')
